package com.hancai.web;

import com.github.pagehelper.PageInfo;
import com.hancai.model.TRecord;
import com.hancai.query.RecordQuery;
import com.hancai.result.R;
import com.hancai.service.RecordService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;


/**
 * @author super
 */
@RestController
public class RecordController {

    @Resource
    private RecordService recordService;

    /**
     * 用户列表分页查询
     *
     * @param current 当前页数
     * @return R
     */
    @GetMapping(value = "/api/records")
    public R recordPage(@RequestParam(value = "current", required = false) Integer current, RecordQuery recordQuery) {

        //required = false 表示参数可以传，也可以不传；
        //required = true 表示参数必须要传，不传会报错；
        if (current == null) {
            current = 1;
        }
        PageInfo<TRecord> pageInfo = recordService.getRecordByPage(current, recordQuery);
        return R.OK(pageInfo);
    }

    @PostMapping(value = "/api/record")
    public R addRecord(RecordQuery recordQuery, @RequestHeader(value = "Authorization") String token) {
        recordQuery.setToken(token);
        int save = recordService.saveRecord(recordQuery);
        return save >= 1 ? R.OK() : R.FAIL();
    }

    @GetMapping(value = "/api/record/{id}")
    public R loadRecord(@PathVariable(value = "id") Integer id) {
        TRecord tRecord = recordService.getRecordById(id);
        return R.OK(tRecord);
    }

    @PutMapping(value = "/api/record")
    public R editRecord(RecordQuery recordQuery, @RequestHeader(value = "Authorization") String token) {
        recordQuery.setToken(token);
        int update = recordService.updateRecord(recordQuery);
        return update >= 1 ? R.OK() : R.FAIL();
    }

    @DeleteMapping(value = "/api/record/{id}")
    public R deleteRecord(@PathVariable(value= "id" )Integer id){
        int delete = recordService.delRecordById(id);
        return delete>=1 ? R.OK() : R.FAIL();
    }

    /**
     * split 方法的作用是将一个字符串按照指定的分隔符（这里是逗号 ,）
     * 拆分成多个子字符串，并将这些子字符串存储到一个数组中返回。
     * 从"1,2,3,4,5"=》["1", "2", "3", "4"]
     * @param ids  ids="1,2,3,4,5";
     * @return R
     */
    @DeleteMapping(value = "/api/record")
    public R batchDelRecord(@RequestParam(value = "ids")String ids){
        List<String> idList = Arrays.asList(ids.split(","));
        int batchDel=recordService.batchDelRecordIds(idList);
        return batchDel>=idList.size() ? R.OK() : R.FAIL();
    }


}
